/*
 * @Author: i@rysa.cn
 * @Date: 2022-05-14 15:57:53
 * @LastEditTime: 2022-05-14 16:01:55
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\wechat\mini\access_token\access_token.go
 */
package accesstoken

import (
	"encoding/json"
	"fmt"

	"gitee.com/rysa/go-utils/request"
	"gitee.com/rysa/go-utils/wechat/mini/config"
	"gitee.com/rysa/go-utils/wechat/mini/params"
)

type accessToken struct {
	*config.MiniConfig
}

const (
	cacheKey = "miniprogram_access_token_key"
)

func NewAccessToken(cfg *config.MiniConfig) *accessToken {
	return &accessToken{cfg}
}

func (ac *accessToken) GetAccessToken() (string, error) {
	tokenKey := cacheKey
	if ac.TokenKey != "" {
		tokenKey = ac.TokenKey
	}
	if !ac.Cache.IsExist(tokenKey) {
		err := ac.GetAccessTokenFromTencent()
		if err != nil {
			return "", err
		}
		ac.GetAccessToken()
	}
	return ac.Cache.Get(tokenKey)
}

func (ac *accessToken) GetAccessTokenFromTencent() error {
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", ac.Appid, ac.AppSecret)
	req := request.NewRequest()
	res, err := req.Get(url)
	if err != nil {
		return err
	}
	var result params.AccessToken
	err = json.Unmarshal(res.Body(), &result)
	if err != nil {
		return err
	}
	tokenKey := cacheKey
	if ac.TokenKey != "" {
		tokenKey = ac.TokenKey
	}
	return ac.Cache.Set(tokenKey, result.AccessToken, result.ExpiresIn-100)
}
